<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="container">
          <el-form size="small" inline label-width="100px">
            <el-form-item
              label="公司名称"
              class="width100"
              style="display: inline-block;"
            >
              <el-input
                v-model="tableFrom.name"
                placeholder="请输入公司名称"
                class="selWidth"
                size="small"
                @keyup.enter.native="getList(1)"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  size="small"
                  class="el-button-solt"
                  @click="getList(1)"
                />
              </el-input>
            </el-form-item>
            <el-form-item label="所在区县" prop="cityId" class="width100">
              <el-cascader
                style="display: block;"
                v-model="tableFrom.cityId"
                :props="searchCityProps"
                :options="searchCityList"
                :placeholder="'请选择'"
                @change="handleCascaderChange"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item
              label="统一社会信用代码"
              label-width="150px"
              style="display: inline-block;"
            >
              <el-input
                v-model="tableFrom.credit_code"
                placeholder="请输入统一社会信用代码"
                class="selWidth"
                size="small"
                @keyup.enter.native="getList(1)"
                maxlength="18"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  size="small"
                  class="el-button-solt"
                  @click="getList(1)"
                />
              </el-input>
            </el-form-item>
          </el-form>
          <el-button
            size="small"
            type="primary"
            @click="onAdd('')"
            v-if="userInfo && userInfo.company_type != 4"
            >添加公司</el-button
          >
        </div>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        name="m1"
        :row-key="
          row => {
            return row.id;
          }
        "
      >
        <el-table-column prop="area_name" label="所在区县"> </el-table-column>
        <el-table-column prop="name" label="公司名称" />
        <el-table-column prop="credit_code" label="统一社会信用代码" />
        <el-table-column prop="create_time" label="成立时间" />
        <el-table-column prop="real_name" label="法人代表" />
        <el-table-column prop="address" label="公司地址" />
        <el-table-column prop="ranking" label="业绩排名"
          ><template slot-scope="{ $index }">{{
            tableFrom.limit * (tableFrom.page - 1) + $index + 1
          }}</template></el-table-column
        >
        <el-table-column prop="people" label="公司成员" />
        <el-table-column prop="tool" label="操作" min-width="120">
          <template slot-scope="scope">
            <!-- <el-link
              type="primary"
              v-if="scope.row.uid == 0"
              @click="bangdingSwitch(scope.row)"
              >绑定</el-link
            > -->
            <el-link type="primary" @click="onAdd(scope.row)" class="link"
              >编辑</el-link
            >
            <!-- <el-link type="danger" @click="deleteStaff(scope.row)"
                >删除员工</el-link
              > -->
            <el-link
              type="primary"
              @click="onDetails(scope.row, scope.$index)"
              class="link"
              >查看</el-link
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <!-- 修改信息 -->
    <el-dialog
      :title="editDialgText"
      :visible.sync="edit_status"
      width="1200px"
      @close="resetForm('editRef')"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        :rules="backrules"
        ref="editRef"
        label-position="top"
      >
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="公司属性" prop="type">
              <el-select
                v-model="addForm.type"
                placeholder="请选择"
                :disabled="disabled"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="城市" prop="city">
              <el-cascader
                style="display: block;"
                v-model="addForm.city"
                :props="cityProps"
                :options="cityList"
                placeholder="请选择"
                :disabled="disabled"
                @change="changeCity"
                ref="cascader"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="公司名称" prop="name">
              <el-input
                v-model="addForm.name"
                placeholder="请输入公司名称"
                :disabled="disabled"
              />
            </el-form-item>
            <el-form-item label="法人代表" prop="real_name">
              <el-input
                v-model="addForm.real_name"
                placeholder="请输入法人代表"
              />
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="addForm.phone" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="统一信用社代码" prop="credit_code">
              <el-input
                v-model="addForm.credit_code"
                placeholder="请输入统一信用社代码"
                :disabled="disabled"
                maxlength="18"
              />
            </el-form-item>
            <el-form-item label="成立日期" prop="effective_date">
              <el-date-picker
                v-model="addForm.effective_date"
                type="date"
                placeholder="选择日期"
                :disabled="disabled"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="经营范围" prop="business_scope">
              <el-input
                type="textarea"
                v-model="addForm.business_scope"
                placeholder="请输入经营范围"
              ></el-input>
            </el-form-item>
            <el-form-item label="公司地址" prop="address">
              <el-input
                v-model="addForm.address"
                placeholder="请输入公司名称"
              /> </el-form-item
          ></el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="edit_status = false">取 消</el-button>
        <el-button type="primary" @click="companySubmitAdd()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 绑定 -->
    <el-dialog
      title="绑定人员"
      :visible.sync="bangding_status"
      width="500px"
      @close="clearBack('bangDingRef')"
      :close-on-click-modal="false"
    >
      <el-form :model="bangDingForm" :rules="bangdingRules" ref="bangDingRef">
        <el-form-item label="姓名" prop="uid">
          <el-select
            v-model="bangDingForm.uid"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in nameOptions"
              :key="item.value"
              :label="`${item.label}-${item.value}`"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearBack('bangDingRef')">取 消</el-button>
        <el-button type="primary" @click="submitBandDin()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { KsCity } from "@/api/staff.js";
import {
  companyList,
  companyUserSearch,
  companyBinding,
  companyAdd,
  citySubLst,
  companyEdit
} from "@/api/company.js";
import Cookies from "js-cookie";
import { roterPre } from "@/settings";
export default {
  name: "",
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!/^1[23456789]\d{9}$/.test(value) && value) {
        callback(new Error("手机号格式不正确!"));
      } else {
        callback();
      }
    };
    // 检查号码是否符合规范，包括长度，类型
    const isCardNo = (rule, card, callback) => {
      // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
      var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/;
      if (reg.test(card) === false) {
        return callback(new Error("请输入正确的身份证号码"));
      } else {
        callback();
      }
    };
    return {
      userInfo: null,
      disabled: false,
      tableFrom: {
        page: 1,
        limit: 20,
        credit_code: "",
        name: "",
        province_id: "",
        city_id: "",
        district_id: "",
        cityId: ""
      },
      listLoading: false,
      tableData: {
        data: [],
        total: 0
      },
      bangding_status: false,
      tabIndex: 0,
      bangdingRules: {
        uid: [{ required: true, message: "请选择绑定人", trigger: "blur" }]
      },
      bangDingForm: {
        uid: null,
        id: ""
      },
      loading: false,
      nameOptions: [],
      addForm: {
        id: undefined,
        type: "",
        real_name: "",
        province_id: "",
        city_id: "",
        district_id: "",
        area_name: "",
        address: "",
        phone: "",
        city: "",
        effective_date: "",
        business_scope: "",
        credit_code: ""
      },
      searchCityList: [],
      searchCityProps: {
        lazy: true,
        label: "name",
        value: "id",
        that: this,
        checkStrictly: true,
        lazyLoad(node, resolve) {
          const { level, data } = node;
          KsCity(data ? data.id : 0)
            .then(res => {
              const nodes = res.data.city.map(item => ({
                id: item.id,
                name: item.area_name,
                leaf: level >= 2
              }));
              resolve(nodes);
            })

            .catch(err => {
              this.$message.error(err.message);
            });
        }
      },
      editDialgText: "新增",
      typeList: [
        {
          label: "省公司",
          value: 1
        },
        {
          label: "市公司",
          value: 2
        },
        {
          label: "区公司",
          value: 3
        },
        {
          label: "营业厅",
          value: 4
        }
      ],
      backrules: {
        type: [{ required: true, message: "请选择公司属性", trigger: "blur" }],
        credit_code: [
          { required: true, message: "请输入统一信用代码", trigger: "blur" }
        ],
        effective_date: [
          { required: true, message: "请输入选择成立日期", trigger: "blur" }
        ],
        phone: [{ required: false, validator: validatePhone, trigger: "blur" }]
      },
      edit_status: false,
      cityList: [],
      cityProps: {
        lazy: true,
        label: "area_name",
        value: "id",
        that: this,
        async lazyLoad(node, resolve) {
          const { level, data } = node;
          const parentCode = level === 0 ? 0 : data.id;
          const nodes = await this.that.getRemoteData(parentCode, level);
          // 去除重复节点
          let nodeFilter = nodes.filter(n => {
            if (!this.that.cityList.includes(n.value)) {
              return n;
            }
          });
          resolve(nodeFilter);
        }
      }
    };
  },
  watch: {},
  computed: {},
  methods: {
    handleCascaderChange(value) {
      // 处理级联选择器值改变事件
      if (value && value.length > 0) {
        switch (value.length) {
          case 1:
            this.tableFrom.province_id = value[0];
            this.tableFrom.city_id = "";
            this.tableFrom.district_id = "";
            break;
          case 2:
            this.tableFrom.province_id = value[0];
            this.tableFrom.city_id = value[1];
            this.tableFrom.district_id = "";
            break;
          case 3:
            this.tableFrom.province_id = value[0];
            this.tableFrom.city_id = value[1];
            this.tableFrom.district_id = value[2];
            break;
        }
      } else {
        this.tableFrom.province_id = "";
        this.tableFrom.city_id = "";
        this.tableFrom.district_id = "";
      }
      this.getList(1);
    },
    getRemoteData(parentCode, level) {
      return new Promise((resolve, reject) => {
        citySubLst(parentCode).then(res => {
          //根据当前登录账号所属筛选指定地区
          if (res.data.data && res.data.data.province_id && level == 0) {
            //去除其他省
            const arr = this.formatData(
              res.data.list.filter(
                item => item.id == res.data.data.province_id
              ),
              level
            );

            resolve(this.formatData(arr, level));
          } else if (res.data.data && res.data.data.city_id && level == 1) {
            //去除其他市
            const arr = this.formatData(
              res.data.list.filter(item => item.id == res.data.data.city_id),
              level
            );
            resolve(this.formatData(arr, level));
          } else if (res.data.data && res.data.data.district_id && level == 2) {
            //去除其他区
            const arr = this.formatData(
              res.data.list.filter(
                item => item.id == res.data.data.district_id
              ),
              level
            );
            resolve(this.formatData(arr, level));
          } else {
            resolve(this.formatData(res.data.list, level));
          }
        });
      });
    },
    formatData(data, level) {
      let districtType = "";
      switch (level) {
        case 0:
          districtType = "province";
          break;
        case 1:
          districtType = "city";
          break;
        case 2:
          districtType = "district";
          break;
        default:
          break;
      }
      return data.map(item => {
        return {
          districtType,
          id: item.id,
          area_name: item.area_name,
          leaf: level >= 2
        };
      });
    },
    companySubList() {
      // companySubList().then(res => {});
    },
    // 列表
    getList(num) {
      this.listLoading = true;
      this.tableFrom.page = num || this.tableFrom.page;
      this.tableData.data = [];

      let param = this.tableFrom;
      delete param.cityId;
      companyList(param)
        .then(res => {
          this.tableData.data = res.data.list;
          this.tableData.total = res.data.count;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
          this.$message.error(res.message);
        });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList("");
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList("");
    },
    // 公司详情
    onDetails(row, index) {
      this.$router.push({
        path: roterPre + "/company/detail",
        query: {
          id: row.id,
          ranking: this.tableFrom.limit * (this.tableFrom.page - 1) + index + 1
        }
      });
    },
    onAdd(row) {
      if (row) {
        this.editDialgText = "编辑";
        this.addForm.id = row.id;
        this.addForm.type = row.type;
        this.addForm.name = row.name;
        this.addForm.real_name = row.real_name;
        this.addForm.province_id = row.province_id;
        this.addForm.city_id = row.city_id;
        this.addForm.district_id = row.district_id;
        this.addForm.area_name = row.area_name;
        this.addForm.address = row.address;
        this.addForm.phone = row.phone;
        this.addForm.effective_date = row.effective_date;
        this.addForm.business_scope = row.business_scope;
        this.addForm.credit_code = row.credit_code;
        this.addForm.city = [row.province_id, row.city_id, row.district_id];
        this.disabled = true;
      } else {
        this.editDialgText = "新增";
      }
      this.edit_status = true;
    },
    remoteMethod(name) {
      if (name !== "") {
        this.loading = true;
        companyUserSearch(name).then(res => {
          this.nameOptions = res.data;
        });
      } else {
        this.nameOptions = [];
      }
    },
    bangdingSwitch(row) {
      this.bangding_status = true;
      this.bangDingForm.id = row.id;
    },
    clearBack(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
      this.bangding_status = false;
      this.edit_status = false;
      this.disabled = false;
    },
    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].clearValidate();
        this.$set(this, "addForm", {
          id: undefined,
          type: "",
          real_name: "",
          province_id: "",
          city_id: "",
          district_id: "",
          area_name: "",
          address: "",
          phone: "",
          city: "",
          effective_date: "",
          business_scope: "",
          credit_code: ""
        });
      });
      this.edit_status = false;
      this.disabled = false;
    },
    //获取添加公司城市选择文本

    changeCity() {
      const cascader = this.$refs.cascader;
      const selectedNodes = cascader.getCheckedNodes();
      this.addForm.area_name = selectedNodes[0].pathLabels.join(",");
    },
    //添加绑定
    submitBandDin() {
      this.$refs["bangDingRef"].validate(valid => {
        if (valid) {
          companyBinding(bangDingForm)
            .then(() => {
              this.$message.success("绑定成功");
              this.bangding_status = false;
              this.getList();
            })
            .catch(e => {
              this.$message.error(e);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //新增公司
    companySubmitAdd() {
      this.$refs["editRef"].validate(valid => {
        if (valid) {
          if (this.addForm.city) {
            this.addForm.province_id = this.addForm.city[0];
            this.addForm.city_id = this.addForm.city[1];
            this.addForm.district_id = this.addForm.city[2];
          }
          const param = JSON.parse(JSON.stringify(this.addForm));
          delete param.id;
          delete param.city;
          if (this.editDialgText == "新增") {
            companyAdd(param)
              .then(res => {
                this.$message.success("新增成功");
                this.getList(1);
                this.clearBack("editRef");
                this.edit_status = false;
              })
              .catch(e => {
                this.$message.error(e);
              });
          }
          if (this.editDialgText == "编辑") {
            companyEdit(this.addForm.id, param)
              .then(res => {
                this.$message.success("编辑成功");
                this.getList(1);
                this.clearBack("editRef");
                this.edit_status = false;
                this.disabled = false;
              })
              .catch(e => {
                this.$message.error(e);
              });
          }
        } else {
          console.log("error submit!!");
        }
      });
    },
    //根据权限设置可以添加公司类型
    setCompanyType() {
      if (this.userInfo) {
        const company_type = this.userInfo.company_type;
        const set_type = this.userInfo.set_type;
        if (company_type == 3) {
          this.typeList = [{ label: "营业厅", value: 4 }];
        }
        if (company_type == 2 || (company_type == 1 && set_type == true)) {
          this.typeList = [
            { label: "区", value: 3 },
            { label: "营业厅", value: 4 }
          ];
        }
        if (company_type == 1 && set_type == false) {
          this.typeList = [
            { label: "市公司", value: 2 },
            { label: "区公司", value: 3 },
            { label: "营业厅", value: 4 }
          ];
        }
      }
    }
  },
  created() {},
  mounted() {
    this.userInfo = JSON.parse(Cookies.get("AdminInfo"));
    this.setCompanyType();
    this.getList();
  }
};
</script>

<style lang="scss" scoped>
.width150 {
  width: 150px;
}
.link {
  margin-right: 6px;
}
</style>
